//
//  ViewControllerEx.swift
//  Extend
//
//  Created by 元穗 on 2017/5/18.
//  Copyright © 2017年 yuansui. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON

public enum ViewType: NSInteger {
    case Load = 0
    case Base = 1
    case Error = 2
}

public enum NetDisableCode: Int {
    case over = -1001
    case dis =  -1009
}

open class ViewConEx: UIViewController, OnNetworkListener, NetworkOpt {
    
    public var showErrorView = false  //判断是否需要显示 error／loading 页面
    let kNetworkDefaultId = -1

    // 修改 error／loading 显示文本
    var errTitle : String = JXLanguageTool.language(String.localized_Common_tips_resetDisable)
    var loadTitle : String = JXLanguageTool.language(String.localized_Common_tips_loading)
   
    lazy var network: Network = {
        return Network(tag: String(describing: self), listener: self);
    }()

    lazy var navBar: NavBar = {
        return NavBar(self)
    }()
 
    func touchErrorView(_ btn: UIButton) {
        self.reTryReqest()
    }
    
    func touchLoadView(_ btn: UIButton) {
        
    }
    
    private lazy var errorView: UIButton = {
        let frame = CGRect(x: 0, y: 0, width: ConstantsEx.kScreenWidth, height: ConstantsEx.kScreenHeight - ConstantsEx.kNavBarHeight)
        let btn = UIButton(frame: frame)
        btn.setTitleColor(App.config?.errTextColor, for: .normal)
        btn.titleLabel?.font = App.config?.errTextFont
        btn.setTitle(self.errTitle, for: .normal)
        btn.addTarget(self, action: #selector(touchErrorView), for: .touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    private lazy var loadingView: UIButton = {
        let frame = CGRect(x: 0, y: 0, width: ConstantsEx.kScreenWidth, height: ConstantsEx.kScreenHeight)
        let btn = UIButton(frame: frame)
        btn.setTitle(self.loadTitle, for: .normal)
        btn.setTitleColor(App.config?.errTextColor, for: .normal)
        btn.titleLabel?.font = App.config?.errTextFont
        btn.addTarget(self, action: #selector(touchLoadView), for: .touchUpInside)
        btn.isHidden = true
        return btn
    }()
  
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true);
        self.navigationItem.setHidesBackButton(true, animated: true)
       
        
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        self.navigationController?.navigationBar.shadowImage = App.config?.navStatusBarImage!
        self.navigationController?.navigationBar.setBackgroundImage(UIImage.setColor(App.config?.navBgColor!), for: UIBarMetrics.default)
        
        self.view.addSubview(errorView)
        self.view.addSubview(loadingView)
    }
    
    
    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        ProgressHUD.dismiss()
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        
        setNavBar(bar: getNavBar());
        setViews();
        initData();
        
    }
    
    public func initNotificationBadge() {
//        
//        NotificationCenter.default.addObserver(self, selector: #selector(redBadgeChange), name: NSNotification.Name(rawValue: ConstantsEx.kAppRedBadge), object: nil)
    }
    
    open func redBadgeChange() {
        
    }
    
    
    open func reTryReqest() {
        
    }


    public func setViewType(type: ViewType) {

        switch type {
        case .Error:
            self.view.bringSubview(toFront: errorView)
            if !showErrorView {
                return
            }
            errorView.setTitle(self.errTitle, for: .normal)
            errorView.isHidden = false
            loadingView.isHidden = true
            return
        case .Load:
            self.view.bringSubview(toFront: loadingView)
            if !showErrorView {
                return
            }
            loadingView.setTitle(self.loadTitle, for: .normal)
            errorView.isHidden = true
            loadingView.isHidden = false
            return
        default:
            errorView.isHidden = true
            loadingView.isHidden = true
            break
        }
    }

    /// 数据初始化
    open func initData() {
        
//        fatalError(ConstantsEx.kNoImpl);
    }
    
    /// 设置导航栏(不是必须的)
    open func setNavBar(bar: NavBar) {
    }

    /// 设置UI属性
    open func setViews() {
        self.view.backgroundColor = App.config?.viewBgColor!
    }

    public func getNavBar() -> NavBar {
        return navBar;
    }
    
    //       Home键监听事件
    open func initializeHomeActive(){
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: .UIApplicationWillResignActive, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive(_:)), name: .UIApplicationDidBecomeActive, object: nil)
    }
    
    open func applicationWillResignActive(_ notification : Notification) {
        viewWillDisappear(true)
    }
    
    open func applicationDidBecomeActive(_ notification : Notification) {
        viewWillAppear(true)
    }
    
    //       键盘监听事件
    open func initializeKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
    }
    
    open func keyboardWillShow(_ notification : Notification){
       
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = kbRect.origin.y - UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
        }
    }
    open func keyboardWillHide(_ notification : Notification){
        let info = notification.userInfo
        let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = kbRect.origin.y - UIScreen.main.bounds.height
        UIView.animate(withDuration: 0.3) {
            self.view.transform = CGAffineTransform(translationX: 0, y: offsetY)
        }
    }
    
    
    
    // MARK: 网络操作

    public func exeNetworkReq<T: HandyJSON>(id: Int, req: NetworkReq, model: T) {
        network.load(id: id, req: req, listener: self, model: model);
    }

    public func exeNetworkReq(id: Int, req: NetworkReq) { //download
        network.load(id: id, req: req, listener: self);
    }

    public func exeNetworkReq<T: HandyJSON>(req: NetworkReq, model: T) {
        exeNetworkReq(id: kNetworkDefaultId, req: req, model: model);
    }

    public func exeNetworkReq(req: NetworkReq) {
        exeNetworkReq(id: kNetworkDefaultId, req: req);
    }

    public func exeNetworkReq(id: Int, req: NetworkReq, listener: OnNetworkListener) {
        exeNetworkReq(id: id, req: req, listener: listener);
    }

    public func exeNetworkReq<T>(id: Int, req: NetworkReq, listener: OnNetworkListener, model: T) where T : HandyJSON {
        exeNetworkReq(id: id, req: req, listener: listener, model: model);
    }

    public func cancelAllNetworkReq() {
        network.cancelAll();
    }

    public func cancelNetworkReq(id: Int) {
        network.cancel(id: id);
    }

    // MARK: 网络回调

    open func onNetworkResponse<T>(id: Int, resp: NetworkResp, model: T) -> AnyObject? where T : HandyJSON {

        return nil;
    }
    
    ///请求成功
    open func onNetworkSuccess(id: Int, result: AnyObject?) {
        
        if showErrorView == true {
            showErrorView = false
            setViewType(type: .Base)
        }
    }

    ///请求失败
    open func onNetworkErr<T>(id: Int, err: T) where T: NetworkErr {
        Log.d("id = " + String(id));
        Log.d("msg = " + err.getMessage());
        Log.d("end============");
        showToast(err.getMessage());
    }

    open func onNetworkProgress(id: Int, progress: Float, total: Int) {
        
    }

    ///网络错误
    open func onNetworkDisable(_ code: NetDisableCode) {
        switch code {
        case .over:
            ProgressHUD.error(JXLanguageTool.language(String.localized_Common_tips_overNet))
            
            if showErrorView {
                errTitle = JXLanguageTool.language(String.localized_Common_tips_resetOverNet)
                setViewType(type: .Error)
            }
            break
        default:
            ProgressHUD.error(JXLanguageTool.language(String.localized_Common_tips_netDisable))
            
            if showErrorView {
                errTitle = JXLanguageTool.language(String.localized_Common_tips_resetDisable)
                setViewType(type: .Error)
            }
            break
        }
        
    }
}




